package main

import (
	"bufio"
	"compress/zlib"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"
)

const (
	FMT1 = "2006-01-02 15:04:05"
	FMT2 = "200601021504"
	FMT3 = "2006-01-02"
)

//homework 1
func convert(str string) string {
	str2time, _ := time.Parse(FMT1, str)
	return str2time.Format(FMT2)
}

//homework 2
func schoolTime() {
	currentDate := "2021-10-30"
	// d := time.Hour * 24

	curSchoolDate, err := time.Parse(FMT3, currentDate)
	if err != nil {
		fmt.Println(err)
		return
	}
	for i := 1; i <= 4; i++ {
		d := time.Hour * 24 * time.Duration(i*7)
		nextSchoolDate := curSchoolDate.Add(d)
		fmt.Println(nextSchoolDate.Format(FMT3))
	}
}

//homework3
func mergeFile(filePath string) {

	fileOut, err := os.OpenFile("data/merge.txt", os.O_APPEND|os.O_CREATE|os.O_TRUNC, 0755) //合并后的文件
	if err != nil {
		log.Fatalln(err)
	}
	defer fileOut.Close()
	writer := bufio.NewWriter(fileOut)

	//开始读取文件
	dirEntries, err := os.ReadDir(filePath)
	if err != nil {
		log.Fatalln("open directory failed:", err)
	}
	for _, dirEntry := range dirEntries {
		if dirEntry.IsDir() == false {
			fileName := dirEntry.Name()
			if strings.HasSuffix(fileName, ".txt") {//找到所有以.txt结尾的文件
				fileIn, err := os.Open(filepath.Join(filePath, fileName))
				if err != nil {
					log.Fatalln(err)
				}
				reader := bufio.NewReader(fileIn)

				for {
					line, err := reader.ReadString('\n')
					fmt.Println(line)
					if err != nil {
						if err != io.EOF {
							log.Fatalln(err)
						} else {
							if line != "" {
								writer.WriteString(line)
							}
							fileIn.Close()
							break //文件末尾
						}
					}
					writer.WriteString(line)
				}
			}
		}
	}
	writer.Flush()

	//压缩文件
	fileOut.Seek(0, 0)
	cpFile, err := os.OpenFile("data/merge.zlib", os.O_APPEND|os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0755)
	if err != nil {
		log.Fatalln(err)
	}
	defer cpFile.Close()

	cpWriter := zlib.NewWriter(cpFile)
	defer cpWriter.Close()
	
	content := make([]byte, 1024)

	for {
		n, err := fileOut.Read(content)
		if err != nil {
			if err != io.EOF {
				log.Fatalln(err)
			} else {
				break
			}
		}
		cpWriter.Write(content[:n])
	}
}

func main() {
	s := "1998-10-01 08:10:00"
	fmt.Println(convert(s))

	schoolTime()

	mergeFile("data")
}
